from playwright.sync_api import Playwright, Page
import platform
import getpass
import random
import time

system = platform.system()
if system.startswith('Windows'):
    EXEC_DIR_PATH = f'C:/Users/{getpass.getuser()}/AppData/Local/Google/Chrome/Application/chrome.exe'
    USER_DIR_PATH = f'C:/Users/{getpass.getuser()}/AppData/Local/Google/Chrome/User_Data'
elif system.startswith('Apple'):
    EXEC_DIR_PATH = f'/Users/{getpass.getuser()}/Library/Application Support/Google/Chrome/Application/chrome'
    USER_DIR_PATH = f'/Users/{getpass.getuser()}/Library/Application Support/Google/Chrome/User_Data'
elif system.startswith('Linux'):
    EXEC_DIR_PATH = f'/home/{getpass.getuser()}/AppData/Local/Google/Chrome/Application/chrome'
    USER_DIR_PATH = f'/home/{getpass.getuser()}/AppData/Local/Google/Chrome/User_Data'


def get_browser_1(playwright: Playwright) -> Page:
    context = playwright.chromium.launch_persistent_context(
        headless=False,
        args=['--start-maximized'],
        # 使用本地浏览器和配置
        executable_path=EXEC_DIR_PATH,
        user_data_dir=USER_DIR_PATH,
        channel='chrome',
        no_viewport=True,
        # 禁用自动化栏
        ignore_default_args=['--enable-automation']
    )
    return context.new_page()


def get_browser_2(playwright: Playwright) -> Page:
    import subprocess
    import time
    '''
    --remote-debugging-port=9999 是指定运行端口，只要没被占用就行
    --user-data-dir 指定运行浏览器的运行数据，新建一个干净目录，不影响系统原来的 数据
    --incognito 隐私模式打开
    --start-maximized 窗口最大化
    --new-window 直接打开网址
    '''
    # 启动命令
    command = f'{EXEC_DIR_PATH} --remote-debugging-port=9999 --remote-allow-origins=* --start-maximized'
    subprocess.Popen(command, shell=True)
    time.sleep(1)
    browser = playwright.chromium.connect_over_cdp('http://localhost:9999')
    context = browser.contexts[0]
    return context.pages[0]


def close_browser(browser: Page):
    print('退出程序')
    browser.close()
    browser.context.close()
    if browser.context.browser is not None:
        browser.context.browser.close()


# 随机打开内容item
def random_click(page: Page, info_list: [], css_selector: str=None, limit: int=3):
    count = 0
    while count < limit and count < len(info_list):
        count = count + 1
        idx = random.randint(0, len(info_list) - 1)
        href = info_list[idx].get_attribute('href')
        page.evaluate(f'window.open("{href}", "_blank");')
        # 暂停3秒
        time.sleep(3)
        # 新标签页(bug：需要切回原标签页)
        page.bring_to_front()
        window_handles = page.context.pages
        current_page = window_handles[-1]
        # 执行回调函数
        if css_selector is not None:
            # 切换标签页
            current_page.bring_to_front()
            info_items = current_page.locator(css_selector).element_handles()
            random_click(current_page, info_items, None, limit)
        # 关闭标签页
        current_page.close()
        # page.bring_to_front()
